<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>区块链商品交易平台</title>
    <!-- 引入Element UI样式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <style>
        body {
            font-family: 'Monaco', sans-serif;
            font-size: larger;
        }

        .el-header {
            background: #fff;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            padding: 0 20px;
        }

        /* 交易表格样式调整 */
        .el-table.transaction-table {
            margin-top: 20px;
        }

        /* 交易标签页样式 */
        .transaction-tabs .el-tabs__item {
            font-size: 16px;
            padding: 0 20px;
        }

        /* 区块信息卡片样式 */
        .block-card {
            margin-bottom: 20px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }

        .block-info-item {
            margin-bottom: 8px;
        }

        .block-hash {
            word-break: break-all;
        }
    </style>
</head>

<body>
    <div id="app">
        <el-container>
            <el-header style="display: flex; align-items: center; justify-content: space-between;">
                <div style="display: flex; align-items: center;">
                    <!-- 导航栏 -->
                    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
                        <el-tab-pane label="商品查询" name="query"></el-tab-pane>
                        <el-tab-pane label="商品上架" name="submit"></el-tab-pane>
                        <el-tab-pane label="等待共识" name="pending"></el-tab-pane>
                        <el-tab-pane label="交易记录" name="transactions"></el-tab-pane>
                        <el-tab-pane label="区块查询" name="blocks"></el-tab-pane>
                    </el-tabs>
                </div>
                <!-- index.html 的导航栏部分 -->
                <div v-if="username" style="margin-left: 20px;">
                    <el-tag type="success">当前用户：{{ username }}</el-tag>
                    <el-tag type="primary" style="margin-left: 10px;">所属组织：{{ organization }}</el-tag>
                    <el-button @click="logout" size="mini" style="margin-left: 10px;">退出登录</el-button>
                </div>

            </el-header>

            <!-- 内容区域 -->
            <el-main>
                <!-- 查询商品 -->
                <div v-show="activeTab === 'query'">
                    <el-row :gutter="20">
                        <el-col :span="8">
                            <el-input v-model="searchId" placeholder="输入商品ID">
                                <el-button slot="append" icon="el-icon-search" @click="getProductById"></el-button>
                            </el-input>
                        </el-col>
                        <el-col :span="8">
                            <el-input v-model="searchOwner" placeholder="输入所有者哈希">
                                <el-button slot="append" icon="el-icon-user" @click="getProductByOwner"></el-button>
                            </el-input>
                        </el-col>
                        <el-col :span="8">
                            <el-button type="primary" @click="getAllProducts">显示所有商品</el-button>
                        </el-col>
                    </el-row>

                    <!-- 商品表格 -->
                    <el-table :data="products" style="width: 100%" v-loading="loading">
                        <el-table-column prop="requestId" label="商品ID" width="240"></el-table-column>
                        <el-table-column prop="org" label="所属组织" width="120"></el-table-column>
                        <el-table-column prop="type" label="类型"
                            :formatter="(row, column, cellValue) => this.$options.filters.shortenType(cellValue)"
                            width="120">
                        </el-table-column>
                        <el-table-column prop="timestamp" label="上架时间" width="180">
                        </el-table-column>
                        <el-table-column prop="block_hash" label="区块哈希" width="240">
                        </el-table-column>
                        <el-table-column prop="amount" label="数量(kw/h)"></el-table-column>
                        <el-table-column prop="price" label="单价(￥)">
                            <template slot-scope="scope">¥{{ scope.row.price.toFixed(2) }}</template>
                        </el-table-column>
                        <el-table-column prop="status" label="状态">
                            <template slot-scope="scope">
                                <el-tag :type="scope.row.status === 0 ? 'success' : 'info'">
                                    {{ scope.row.status === 0 ? '在售' : '已售' }}
                                </el-tag>
                                <el-button v-if="scope.row.status === 0" size="mini" type="danger"
                                    @click="handleBuy(scope.row)">购买</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column prop="owner" label="所有者" width="180">
                            <template slot-scope="scope">
                                <el-tooltip :content="scope.row.owner">
                                    <span>{{ scope.row.owner | shortHash }}</span>
                                </el-tooltip>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>

                <!-- 上架商品 -->
                <div v-show="activeTab === 'submit'">
                    <el-form :model="form" label-width="80px">
                        <el-form-item label="商品类型">
                            <el-input v-model="form.type"></el-input>
                        </el-form-item>
                        <el-form-item label="数量">
                            <el-input-number v-model="form.amount" :min="1"></el-input-number>
                        </el-form-item>
                        <el-form-item label="单价">
                            <el-input v-model="form.price" type="number">
                                <template slot="append">元</template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="证书文件">
                            <el-upload action="#" :auto-upload="false" :on-change="handleCertificate">
                                <el-button size="small">点击上传</el-button>
                            </el-upload>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="submitProduct">立即上架</el-button>
                        </el-form-item>
                    </el-form>
                </div>

                <!-- 交易记录 -->
                <div v-show="activeTab === 'transactions'">
                    <el-tabs type="card">
                        <el-tab-pane label="我的购买">
                            <el-table :data="buyTransactions" style="width: 100%" v-loading="loading">
                                <el-table-column prop="requestId" label="交易ID" width="240"></el-table-column>
                                <el-table-column prop="productId" label="商品ID" width="240"></el-table-column>
                                <el-table-column prop="amount" label="数量"></el-table-column>
                                <el-table-column prop="balance" label="交易金额">
                                    <template slot-scope="scope">¥{{ scope.row.balance.toFixed(2) }}</template>
                                </el-table-column>
                                <el-table-column prop="timestamp" label="交易时间"></el-table-column>
                                <el-table-column prop="buyer" label="买家" width="180">
                                    <template slot-scope="scope">
                                        <el-tooltip :content="scope.row.buyer">
                                            <span>{{ scope.row.buyer | shortHash }}</span>
                                        </el-tooltip>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="block_hash" label="区块哈希"></el-table-column>
                            </el-table>
                        </el-tab-pane>

                        <el-tab-pane label="我的出售">
                            <el-table :data="sellTransactions" style="width: 100%" v-loading="loading">
                                <el-table-column prop="requestId" label="交易ID" width="240"></el-table-column>
                                <el-table-column prop="productId" label="商品ID" width="240"></el-table-column>
                                <el-table-column prop="amount" label="数量"></el-table-column>
                                <el-table-column prop="balance" label="交易金额">
                                    <template slot-scope="scope">¥{{ scope.row.balance.toFixed(2) }}</template>
                                </el-table-column>
                                <el-table-column prop="timestamp" label="交易时间"></el-table-column>
                                <el-table-column prop="buyer" label="买家" width="180">
                                    <template slot-scope="scope">
                                        <el-tooltip :content="scope.row.buyer">
                                            <span>{{ scope.row.buyer | shortHash }}</span>
                                        </el-tooltip>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="block_hash" label="区块哈希"></el-table-column>
                            </el-table>
                        </el-tab-pane>
                    </el-tabs>
                </div>

                <!-- 等待共识 -->
                <div v-show="activeTab === 'pending'">
                    <el-table :data="pendingTransactions" style="width: 100%" v-loading="loading">
                        <el-table-column prop="requestId" label="请求ID" width="240"></el-table-column>
                        <el-table-column prop="type" label="类型" width="120"></el-table-column>
                        <el-table-column prop="timestamp" label="提交时间" width="180"></el-table-column>
                        <el-table-column label="状态">
                            <template slot-scope="scope">
                                <el-tag type="warning">等待共识中...</el-tag>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <!-- 区块查询 -->
                <div v-show="activeTab === 'blocks'">
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-input v-model="blockSearch" placeholder="输入区块高度或哈希" clearable>
                                <el-button slot="append" icon="el-icon-search" @click="searchBlock"></el-button>
                            </el-input>
                        </el-col>
                        <el-col :span="12">
                            <el-button type="primary" @click="getAllBlocks">获取全部区块</el-button>
                        </el-col>
                    </el-row>

                    <div v-if="blocksLoading" style="text-align: center; margin: 20px 0;">
                        <el-progress type="circle" :percentage="progressPercent" :status="progressStatus"></el-progress>
                        <p>正在查询节点 {{ currentNodePort }}...</p>
                    </div>

                    <div v-if="blocks.length > 0">
                        <el-card class="block-card" v-for="block in blocks" :key="block.hash">
                            <div slot="header" class="clearfix">
                                <span>区块 #{{ block.index }}</span>
                                <el-tag type="success" style="float: right; margin-left: 10px;">高度: {{ block.index
                                    }}</el-tag>
                                <el-tag style="float: right;">哈希: {{ block.hash | shortHash }}</el-tag>
                            </div>
                            <div class="block-info-item">
                                <strong>前一个区块哈希:</strong>
                                <span v-if="block.previousHash">{{ block.previousHash }}</span>
                                <span v-else>无 (创世区块)</span>
                            </div>
                            <div class="block-info-item">
                                <strong>时间戳:</strong> {{ new Date(block.timestamp).toLocaleString() }}
                            </div>
                            <div class="block-info-item">
                                <strong>区块信息:</strong>
                                <pre
                                    style="margin-top: 10px; background: #f5f5f5; padding: 10px; border-radius: 4px;">{{ formatBlockInfo(block.blockInfo) }}</pre>
                            </div>
                            <div class="block-info-item block-hash">
                                <strong>完整哈希:</strong> {{ block.hash }}
                            </div>
                        </el-card>
                    </div>

                    <div v-if="blocks.length === 0 && !blocksLoading" style="text-align: center; margin-top: 50px;">
                        <el-empty description="暂无区块数据"></el-empty>
                    </div>
                </div>
            </el-main>
        </el-container>
        <!-- 购买表单弹窗 -->
        <el-dialog :visible.sync="buyDialogVisible" title="购买商品 - 上传密钥和证书">
            <el-form :model="buyForm" label-width="120px">
                <el-form-item label="证书文件">
                    <el-upload action="#" :auto-upload="false" :on-change="handleBuyCertificate">
                        <el-button size="small">点击上传</el-button>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="buyDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmBuy">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>

    <!-- 引入Vue和Element UI -->
    <script src="https://unpkg.com/vue@2.6.14/dist/vue.js"></script>
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>

    <script>
        new Vue({
            el: '#app',
            created() {
                if (!localStorage.getItem('username')) {
                    window.location.href = 'login.html';
                }
                if (this.username) {
                    this.eventSource = new EventSource(`http://localhost:9090/sse/subscribe/${this.username}`);
                    this.eventSource.onmessage = (event) => {
                        const completedRequestId = event.data.trim(); // 去除前后空格
                        console.log('SSE event received for:', completedRequestId);
                        // 过滤对应的请求
                        this.pendingTransactions = this.pendingTransactions.filter(
                            t => t.requestId !== completedRequestId
                        );
                        this.$message.success(`请求 ${completedRequestId} 已完成`);
                        // 刷新相关数据
                        if (this.activeTab === 'transactions') this.getTransactions();
                        if (this.activeTab === 'query') this.getAllProducts();
                    };
                }
            },
            beforeDestroy() {
                if (this.eventSource) {
                    this.eventSource.close();
                }
            },
            data() {
                return {
                    username: localStorage.getItem('username') || '',
                    organization: localStorage.getItem('organization') || '',
                    activeTab: 'query',
                    searchId: '',
                    searchOwner: '',
                    products: [],
                    loading: false,
                    form: {
                        type: '',
                        amount: 1,
                        price: 0
                    },
                    certificate: null,
                    buyDialogVisible: false,
                    buyForm: {
                        certificate: null
                    },
                    currentBuyProduct: null,
                    buyTransactions: [],
                    sellTransactions: [],

                    pendingTransactions: [], // 等待共识的交易

                    // 区块查询相关数据
                    blockSearch: '',
                    blocks: [],
                    blocksLoading: false,
                    currentNodePort: 8001,
                    progressPercent: 0,
                    progressStatus: null,
                    nodePorts: [8001, 8002, 8003, 8004]
                }
            },
            filters: {
                shortHash(value) {
                    return value ? `${value.substring(0, 6)}...${value.slice(-4)}` : ''
                },
                // 类型字段缩短显示
                shortenType(value) {
                    return value.length > 10 ? `${value.substring(0, 10)}...` : value;
                }
            },
            methods: {
                signature() { },

                logout() {
                    localStorage.removeItem('username');
                    localStorage.removeItem('organization');
                    window.location.href = 'login.html';  // 修改退出跳转逻辑
                },
                // 获取所有商品
                async getAllProducts() {
                    this.loading = true
                    for (let i = 0; i < this.nodePorts.length; i++) {
                        this.currentNodePort = this.nodePorts[i];
                        this.progressPercent = (i / this.nodePorts.length) * 100;

                        try {
                            const url = `http://172.22.132.90:${this.currentNodePort}/scan`;
                            const response = await fetch(url);

                            if (response.ok) {
                                const data = await response.json();
                                if (data && (Array.isArray(data) ? data.length > 0 : Object.keys(data).length > 0)) {
                                    this.progressStatus = 'success';
                                    this.progressPercent = 100;
                                    return data;
                                }
                            }
                        } catch (error) {
                            console.error(`节点 ${this.currentNodePort} 查询失败:`, error);
                            // 继续尝试下一个节点
                        }
                    }
                },
                // 新增 handleTabClick 方法
                handleTabClick(tab) {
                    // 根据选中的标签页重置搜索条件
                    if (tab.name === 'submit') {
                        this.searchId = '';
                        this.searchOwner = '';
                    } else if (tab.name === 'transactions') {
                        this.getTransactions();
                    } else if (tab.name === 'blocks') {
                        this.blocks = [];
                    }
                },

                // 新增 getProductByOwner 方法
                async getProductByOwner() {
                    if (!this.searchOwner) {
                        this.$message.warning('请输入所有者哈希');
                        return;
                    }
                    try {
                        const res = await fetch(`http://localhost:9090/product/owner/${this.searchOwner}`);
                        if (res.ok) {
                            this.products = await res.json();
                        } else {
                            this.$message.error('查询失败');
                        }
                    } catch (error) {
                        this.$message.error('网络错误');
                    }
                },
                // 购买操作
                handleBuy(product) {
                    this.currentBuyProduct = product;
                    this.buyDialogVisible = true;
                },
                handleBuyCertificate(file) {
                    this.readFile(file.raw).then(content => {
                        this.buyForm.certificate = content;
                    });
                },
                async confirmBuy() {
                    const { certificate } = this.buyForm;
                    if (!certificate) {
                        this.$message.warning('请上传证书文件');
                        return;
                    }
                    // 构造请求体
                    const requestBody = {
                        transaction: {
                            product_id: this.currentBuyProduct.requestId,
                            buyer: localStorage.getItem('username') || '',
                            saler: this.currentBuyProduct.owner, // 修正字段名
                            amount: this.currentBuyProduct.amount
                        },
                        price: this.currentBuyProduct.price,
                        certificate: certificate,
                        username: localStorage.getItem('username') || '' // 添加username
                    };
                    const res = await fetch('http://localhost:9090/transaction/submit', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify(requestBody)
                    });
                    const data = await res.json();
                    if (res.ok) {
                        this.pendingTransactions.push({
                            requestId: data.requestId,
                            type: '商品购买',
                            timestamp: new Date().toISOString()
                        });
                        this.$message.success('交易已发起');
                    }
                },

                handleCertificate(file) {
                    this.readFile(file.raw).then(content => {
                        this.certificate = content;
                    });
                },

                // 提交商品
                async submitProduct() {
                    const payload = {
                        product: this.form,
                        certificate: this.certificate, // 上传证书内容
                        username: this.username // 传递当前登录用户名
                    }

                    try {
                        const res = await fetch('http://localhost:9090/product/submit', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify(payload)
                        })
                        const data = await res.json();
                        if (res.ok) {
                            this.pendingTransactions.push({
                                requestId: data.requestId,
                                type: '商品上架',
                                timestamp: new Date().toISOString()
                            });
                            this.$message.success('已提交等待共识');
                        }
                    } catch (e) {
                        this.$message.error('提交失败');
                    }
                },
                async getProductById() {
                    if (!this.searchId) {
                        this.$message.warning('请输入商品ID');
                        return;
                    }
                    try {
                        const res = await fetch(`http://localhost:9090/product/${this.searchId}`);
                        if (res.ok) {
                            const product = await res.json();
                            this.products = [product]; // 查询到的单个商品
                        } else {
                            this.$message.error('商品不存在或网络错误');
                        }
                    } catch (error) {
                        this.$message.error('请求失败，请检查网络');
                    }
                },
                async getTransactions() {
                    if (!this.username) return;

                    this.loading = true;
                    try {
                        // 获取购买记录
                        const buyRes = await fetch(`http://172.22.132.90:8001/transaction/buyer/${this.username}`);
                        this.buyTransactions = await buyRes.json();

                        // 获取出售记录
                        const sellRes = await fetch(`http://localhost:9090/transaction/saler/${this.username}`);
                        this.sellTransactions = await sellRes.json();
                    } catch (e) {
                        this.$message.error('获取交易记录失败');
                    } finally {
                        this.loading = false;
                    }
                },
                // 通用文件读取方法
                readFile(file) {
                    return new Promise((resolve) => {
                        const reader = new FileReader()
                        reader.onload = () => resolve(reader.result)
                        reader.readAsText(file)
                    })
                },

                // 区块查询相关方法
                async searchBlock() {
                    if (!this.blockSearch) {
                        this.$message.warning('请输入区块高度或哈希');
                        return;
                    }

                    this.blocksLoading = true;
                    this.progressPercent = 0;
                    this.progressStatus = null;

                    try {
                        // 先尝试作为高度查询
                        if (/^\d+$/.test(this.blockSearch)) {
                            const block = await this.tryGetBlockFromNodes(`height/${this.blockSearch}`);
                            if (block) {
                                this.blocks = [block];
                                this.$message.success('区块查询成功');
                                return;
                            }
                        }

                        // 尝试作为哈希查询
                        const block = await this.tryGetBlockFromNodes(`hash/${this.blockSearch}`);
                        if (block) {
                            this.blocks = [block];
                            this.$message.success('区块查询成功');
                            return;
                        }

                        this.$message.error('未找到指定区块');
                        this.blocks = [];
                    } catch (error) {
                        this.$message.error('区块查询失败: ' + error.message);
                    } finally {
                        this.blocksLoading = false;
                    }
                },

                async getAllBlocks() {
                    this.blocksLoading = true;
                    this.progressPercent = 0;
                    this.progressStatus = null;

                    try {
                        const blocks = await this.tryGetBlockFromNodes();
                        if (blocks && blocks.length > 0) {
                            this.blocks = blocks;
                            this.$message.success(`获取到 ${blocks.length} 个区块`);
                        } else {
                            this.$message.warning('未获取到任何区块数据');
                            this.blocks = [];
                        }
                    } catch (error) {
                        this.$message.error('获取区块失败: ' + error.message);
                        this.blocks = [];
                    } finally {
                        this.blocksLoading = false;
                    }
                },

                // 从多个节点尝试获取区块数据
                async tryGetBlockFromNodes() {
                    for (let i = 0; i < this.nodePorts.length; i++) {
                        this.currentNodePort = this.nodePorts[i];
                        this.progressPercent = (i / this.nodePorts.length) * 100;

                        try {
                            const url = `http://172.22.132.90:${this.currentNodePort}/scan`;
                            const response = await fetch(url);

                            if (response.ok) {
                                const data = await response.json();
                                if (data && (Array.isArray(data) ? data.length > 0 : Object.keys(data).length > 0)) {
                                    this.progressStatus = 'success';
                                    this.progressPercent = 100;
                                    return data;
                                }
                            }
                        } catch (error) {
                            console.error(`节点 ${this.currentNodePort} 查询失败:`, error);
                            // 继续尝试下一个节点
                        }
                    }

                    this.progressStatus = 'exception';
                    return null;
                },

                // 格式化区块信息
                formatBlockInfo(blockInfo) {
                    if (Array.isArray(blockInfo)) {
                        if (typeof blockInfo[0] === 'string') {
                            return blockInfo.join('\n');
                        } else {
                            return JSON.stringify(blockInfo, null, 2);
                        }
                    } else if (typeof blockInfo === 'object') {
                        return JSON.stringify(blockInfo, null, 2);
                    }
                    return blockInfo;
                }
            }
        })
    </script>
</body>

</html>